package com.key.util;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author dzl
 * @Date 2021/12/3 5:51 下午
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 通过接口
     *
     * @param clazz /
     * @param <T> /
     * @return /
     */
    public static <T> T getTByInterfaceOne(Class<T> clazz) {
        Map<String, T> beans = applicationContext.getBeansOfType(clazz);
        for (String key : beans.keySet()) {
            return beans.get(key);
        }
        throw new RuntimeException("请实现KeyCenter接口");
    }

    /**
     * 获取applicationContext
     *
     * @return /
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean
     *
     * @param name /
     * @return /
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 通过class获取Bean
     *
     * @param clazz /
     * @param <T> /
     * @return /
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name /
     * @param clazz /
     * @param <T> /
     * @return /
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }

}

